package sandbox.swing;

import java.io.Serializable;
import javax.swing.AbstractSpinnerModel;

class SpinnerIntegerModel extends AbstractSpinnerModel implements Serializable {

    private int stepSize;
    private Integer value;

    public SpinnerIntegerModel(Integer value, int stepSize) {
        this.value = value;
        this.stepSize = stepSize;
    }

    public SpinnerIntegerModel() {
        this(null, 1);
    }

    public void setStepSize(int stepSize) {
        if(stepSize != this.stepSize) {
            this.stepSize = stepSize;
            fireStateChanged();
        }
    }

    public int getStepSize() {
        return stepSize;
    }

    private Integer incrValue(int dir) {
        Integer newValue;
        if(value == null) {
            newValue = null;
        } else {
            newValue = value + (stepSize * dir);
        }
        return newValue;
    }

    @Override
    public Object getNextValue() {
        return incrValue(+1);
    }

    @Override
    public Object getPreviousValue() {
        return incrValue(-1);
    }

    public Number getNumber() {
        return value;
    }

    @Override
    public Object getValue() {
        return value;
    }

    @Override
    public void setValue(Object value) {
        if((value != null) && !(value instanceof Integer)) {
            throw new IllegalArgumentException("illegal value");
        }
        if(value == null && this.value != null) {
            this.value = null;
            fireStateChanged();
        }
        if(value != null && !value.equals(this.value)) {
            this.value = (Integer) value;
            fireStateChanged();
        }
    }
}
